/** 
* This class called by accountAssignmentProcess. It divides 
* records into batch size of 20 and create Apex Batch job
*
* Client - Cisco Systems (Linksys)
* 
* Author - Manu Dhingra
* Cretaed - Feb 2010
* Last Update - March 2010
* 
** test
** line 1**
line 2?***/

global class accountAssignmentBatch implements Database.Batchable<sObject>,Database.AllowsCallouts{
    global  dateTime lastRunTime;
    global  String query;
    global  String email;
   

    global database.querylocator start(Database.BatchableContext BC){
    
    User[] userId = [SELECT ID FROM USER WHERE name = 'Integration User' LIMIT 1];
     
    if (lastRunTime == null){
        lastRunTime = system.now() - 1;
        } 

        return Database.getQueryLocator([SELECT id, name, billingCountry, billingstate, ownerId, Type
									        FROM Account 
									        WHERE CreatedDate > :lastRunTime
									        AND Type <> 'Registered'
									        AND CreatedByID = :userId[0].Id
									        AND ownerId = :userId[0].ID ]);
        }
 
    global void execute(Database.BatchableContext BC, List<sObject> scope){
        
        List<Account> acct = new List<Account>();
        
        for(sObject s : scope){
            Account a = (Account)s;
Integer i = 0 ; 
system.debug('Account Counter '+i + '  ' + a.id);
i++;
          	Named_Account_Assignments__c [] assigneeNA = [SELECT country__c,customer_name__c, ownerid
									                          FROM  Named_Account_Assignments__c
									                          WHERE customer_name__c = :a.name
									                          AND country__c = :a.billingCountry
									                          LIMIT 1];
                
          if (assigneeNA.size()> 0) {
			//assign the owner Id for the Named Account Assignment
            system.debug('Name Account Assignment ' + a.id);
            a.ownerId =  assigneeNA[0].ownerid;
            acct.add(a);
          	}
            // Checking for Distributor Account Assignment
            
            else if ( a.Type == 'Distributor' ) {
            	Account_Assignment__c [] distyAccOwner = [SELECT Ownerid
								                          FROM  Account_Assignment__c
								                          WHERE Country__c = :a.billingCountry
								                          AND Customer_Type__c = :a.Type
								                          LIMIT 1];
             	if (distyAccOwner.size() > 0) {	
             		system.debug('Distrubutor Account Assignment ' + a.id);
             		a.ownerId =  distyAccOwner[0].ownerid;
					acct.add(a);
             		}            	
            	}
            // Checking for Direct Retailer Account Assignment
            	
            else if ( a.Type == 'Direct Retailer' ){
            	Account_Assignment__c [] DRAccOwner = [SELECT Ownerid
								                          FROM  Account_Assignment__c
								                          WHERE Country__c 		= :a.billingCountry
								                          AND State_Province__C = :a.billingstate
								                          AND Customer_Type__c 	= :a.Type
								                          LIMIT 1];
             	if (DRAccOwner.size()> 0) {	
             		system.debug('Direct Retailer Account Assignment ' + a.id);
             		a.ownerId =  DRAccOwner[0].ownerid;
					acct.add(a);
             		}            	
            	}
        }

        update acct;
//for (Account a : acct){
//      System.Debug ('Account Id' + acct.id +'and New Owner Id '+acct.Ownerid )}
    }

    global void finish(Database.BatchableContext BC){
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {email});
        mail.setReplyTo('batch@acme.com');
        mail.setSenderDisplayName('Batch Processing');
        mail.setSubject('Batch Process Completed');
        mail.setPlainTextBody('Batch Process has completed');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }

    public static testMethod void testBatch() {
// Enter Comments here

        Test.StartTest();
        
        accountAssignmentBatch reassign = new accountAssignmentBatch();
//      reassign.query='SELECT id, name, billingCountry, billingstate FROM Account  LIMIT 100 ';
        reassign.email='madhingr@cisco.com';
        ID batchprocessid = Database.executeBatch(reassign);
        Test.StopTest();
        }
        

}